package com.swt.gap.config.shiro;

import com.swt.gap.model.entity.SysRole;
import com.swt.gap.model.entity.SysUser;
import com.swt.gap.service.SysRoleService;
import com.swt.gap.service.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * created by lanshengyuan on 2019/10/24
 */
public class CustomRealm extends AuthorizingRealm {


    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("授权doGetAuthorizationInfo");

        SysUser sysUser = (SysUser) principalCollection.getPrimaryPrincipal();
        //获取用户角色
        List<SysRole>  sysRoleList = sysRoleService.getUserRoleByUserName(sysUser.getUserName());
        List<String> stringRoleList = new ArrayList<>();

        for (SysRole sysRole:sysRoleList){
            stringRoleList.add(sysRole.getRoleName());

        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(stringRoleList);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("认证doGetAuthenticationInfo");

//        LocalDate exDate = LocalDate.parse("2021-01-16");
//        LocalDate nowDate = LocalDate.now();
//        if (nowDate.isAfter(exDate)) {
//            return null;
//        }

        String username = (String) authenticationToken.getPrincipal();

        SysUser sysUser = sysUserService.getUserByName(username);
        if(null == sysUser || null == sysUser.getPassword() || "".equals(sysUser.getPassword())){
            return null;
        }
        if(!sysUser.getActivated()){
            throw new AuthenticationException("账号未启用");
        }

        return new SimpleAuthenticationInfo(sysUser,sysUser.getPassword(),this.getClass().getName());
    }

}
